package com.bw.demo_coroutine

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import kotlinx.coroutines.*

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        println(Thread.currentThread())//主线程
        val coroutineScope = CoroutineScope(Dispatchers.Default)
        coroutineScope.launch {
            println(Thread.currentThread()) //子线程
            val data = getData() //模拟网络请求数据
            withContext(Dispatchers.Main){
                println(Thread.currentThread())
                Toast.makeText(this@MainActivity, data, Toast.LENGTH_LONG).show()
            }
        }
    }
}

suspend fun getData(): String{
    delay(2000)
    return "我是网络请求得到的数据"
}